package route

import (
	"fmt"
	"more_ssh/conf"
	"more_ssh/sql"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

func listAccount(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "请求的参数有误，请检查 id 参数是否是整数",
		})
		return
	}

	// pagedb := sql.Paginate(page, pagesize)
	var account []sql.Account
	// conf.DB.Scopes(pagedb).Find(suer)
	conf.DB.Where("host_id=?", id).Find(&account)

	c.JSON(http.StatusOK, gin.H{
		"accounts": account,
	})
}

func postAccount(c *gin.Context) {
	account := &sql.Account{}

	err := c.BindJSON(account)
	if err != nil {
		fmt.Println(err.Error())
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "请求参数解析失败，请检查参数是否有误",
		})
		return
	}

	fmt.Printf("%#v", account)
	if account.Password != "" {
		account.IsNull = true
	}

	result := conf.DB.Create(account)
	if result.Error != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": result.Error.Error(),
		})
		return
	}

	c.JSON(http.StatusCreated, gin.H{
		"msg":     "创建账号成功",
		"account": account,
	})
}

func putAccount(c *gin.Context) {
	// id := c.Param("id") //取出参数中的id
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "请检查id是否是数字",
		})
		return
	}
	//查找数据库中符合条件的用户
	account := &sql.Account{}
	err = c.BindJSON(account)
	if err != nil {
		fmt.Println(err.Error())
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "请求参数解析失败，请检查参数是否有误",
		})
		return
	}
	account.ID = uint(id)
	conf.DB.Save(account)
	c.JSON(http.StatusOK, gin.H{
		"msg": "更新成功",
	})
}

func deleteAccount(c *gin.Context) {
	id := c.Param("id")
	_, err := strconv.Atoi(id)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "请检查id是否是数字",
		})
		return
	}
	account := &sql.Account{}
	len := conf.DB.Where("id=?", id).First(account).RowsAffected
	if len != 1 {
		c.JSON(http.StatusNotFound, gin.H{
			"msg": "没有找到id " + id + " 的账号",
		})
		return
	}

	result := conf.DB.Delete(account)

	if result.Error != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": result.Error.Error(),
		})
		return
	}

	c.JSON(http.StatusNoContent, gin.H{
		"msg":     "删除成功",
		"account": account,
	})
}
